import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:get/instance_manager.dart';
import 'package:image_crop/image_crop.dart';

class CropWidget extends StatefulWidget {
  final File source;

  const CropWidget({Key key, @required this.source}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _CropWidget();
  }
}

class _CropWidget extends State<CropWidget> {
  final cropKey = GlobalKey<CropState>();

  Future<void> _cropImage() async {
    final scale = cropKey.currentState.scale;
    final area = cropKey.currentState.area;
    if (area == null) {
      // cannot crop, widget is not setup
      return;
    }

    // scale up to use maximum possible number of pixels
    // this will sample image in higher resolution to make cropped image larger
    final sample = await ImageCrop.sampleImage(
      file: widget.source,
      preferredSize: (2000 / scale).round(),
    );

    final file = await ImageCrop.cropImage(
      file: sample,
      area: area,
    );

    Get.back(result: file);
    sample.delete();

    debugPrint('$file');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: Color(0xffEA5504),
        title: Text(
          '剪切图片',
          style: TextStyle(
            color: Colors.white,
            fontSize: 17,
          ),
        ),
        iconTheme: IconThemeData(
          color: Colors.white,
        ),
        actions: [
          GestureDetector(
            onTap: _cropImage,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              child: Center(
                child: Text(
                  "剪切",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
      body: Crop.file(widget.source, key: cropKey),
    );
  }
}
